package com.jqsoft.launcher.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.widget.Toast;

import com.jqsoft.launcher.activity.bean.TiJiaoSFBean;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileService {
	private Context context;

	public FileService(Context context) {
		this.context = context;
	}

	/**
	 * 把用户名和密码保存到手机内存
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param filename
	 *            文件会被保存到 /data/data/<当前包名>/files/filename
	 * 
	 *            保存到哪个文件中
	 * @return
	 */
	public boolean saveToRom(String sPersonID, String sNo, String sName,
			String sCardNo, String suifangtype, String suifangData,
			String filename) throws Exception {
		// 以私有的方式打开一个文件的输出流 文件的名字叫 filename
		FileOutputStream fos = context.openFileOutput(filename,
				Context.MODE_APPEND);
		String date = DateTools
				.getFormatStringByDF_YYYY_MM_DD_HH_MM(new Date());
		String result = sPersonID + ":jqkjgjq:" + sNo + ":jqkjgjq:" + sName
				+ ":jqkjgjq:" + sCardNo + ":jqkjgjq:" + date + ":jqkjgjq:"
				+ suifangtype + ":jqkjgjq:" + suifangData + ":::jqkjgjq:::";
		fos.write(result.getBytes());
		fos.flush();
		fos.close();
		return true;
	}

	/**
	 * 获取对应文件里面存放的用户名和密码
	 * 
	 * @param filename
	 * @return
	 */
	public List<TiJiaoSFBean> getUserInfo(String filename) throws Exception {
		File file = new File("/data/data/com.jqsoft.launcher/files/" + filename);
		if (!file.exists()) {
			return null;
		}
		;
		// FileInputStream fis = new FileInputStream(file);
		FileInputStream fis = context.openFileInput(filename);

		byte[] result = StreamTools.getBytes(fis);
		String info = new String(result);
		// username:password
		String[] infoarray = info.split(":::jqkjgjq:::");
		List<TiJiaoSFBean> infoList = new ArrayList<TiJiaoSFBean>();
		TiJiaoSFBean tijiao;
		for (int i = 0; i < infoarray.length; i++) {
			if (StringUtils.isNotBlank(infoarray[i])) {
				String[] infos = infoarray[i].split(":jqkjgjq:");
				tijiao = new TiJiaoSFBean(infos[0], infos[1], infos[2],
						infos[3], infos[4], infos[5], infos[6]);
				infoList.add(tijiao);
				// Map<String, String> userinfo = new HashMap<String, String>();
				// userinfo.put("sNo", infos[0]);
				tijiao = null;
			}
		}
		return infoList;
	}

	public boolean removeFromRom(int index, String filename) throws Exception {
		StringBuffer buffer = new StringBuffer();
		// String chanageResult;
		FileInputStream fis = context.openFileInput(filename);
		byte[] result = StreamTools.getBytes(fis);
		String info = new String(result);
		// username:password
		String[] infoarray = info.split(":::jqkjgjq:::");
		for (int i = 0; i < infoarray.length; i++) {
			if (StringUtils.isNotBlank(infoarray[i]) && i != index) {
				buffer.append(infoarray[i] + ":::jqkjgjq:::");
			}
		}
		FileOutputStream fos = context.openFileOutput(filename,
				Context.MODE_PRIVATE);
		fos.write(buffer.toString().getBytes());
		fos.flush();
		fos.close();
		return true;
	}

	public boolean updateFromRom(int index, String sPersonID, String sNo,
			String sName, String sCardNo, String suifangtype,
			String suifangData, String filename) throws Exception {
		boolean result2 = false;
		boolean result = saveToRom(sPersonID, sNo, sName, sCardNo, suifangtype,
				suifangData, filename);
		if (result) {
			result2 = removeFromRom(index, filename);
		}
		return result2;
	}

	/**
	 * 保存数据到sd卡上
	 *
	 * @param username
	 * @param password
	 * @param filename
	 *            文件名
	 * @return
	 * @throws Exception
	 */
	public boolean saveToSDcard(String username, String password,
			String filename) throws Exception {
		// 2.1的平台 /sdcard/
		// File file = new File("/mnt/sdcard/", filename);
		// 判断sd卡的状态
		// Environment.getExternalStorageState(); // 获取外部存储设备的状态

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			File file = new File(Environment.getExternalStorageDirectory(),
					filename);
			FileOutputStream fos = new FileOutputStream(file);
			String result = username + ":" + password;
			fos.write(result.getBytes());
			fos.flush();
			fos.close();
			return true;
		} else {
			Toast.makeText(context, "sd卡不可用", 0).show();
			return false;
		}
	}

	/**
	 * 保存数据到sharedpreference里面
	 *
	 * @param username
	 * @param password
	 * @param filename
	 *            sp的名字
	 * @return
	 */
	public boolean saveToSp(String username, String password, String filename) {

		SharedPreferences sp = context.getSharedPreferences(filename,
				Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putString("username", username);
		editor.putInt("myint", 5);
		editor.putBoolean("myboolean", false);
		editor.putString("password", password);

		editor.commit();// 把数据真正的提交到sharedpreference里面
		return true;
	}

	public boolean removeFromRom2(int index, String mangeType, String filename)
			throws Exception {
		StringBuffer buffer = new StringBuffer();
		// String chanageResult;
		FileInputStream fis = context.openFileInput(filename);
		byte[] result = StreamTools.getBytes(fis);
		String info = new String(result);
		// username:password
		String[] infoarray = info.split(":::jqkjgjq:::");
		int currentIndex = 0;
		for(int i=0;i<infoarray.length;i++){
			String[] te	 = infoarray[i].split(":jqkjgjq:");
			if(te[5].equals(mangeType)){
				if(currentIndex==index){
					removeFromRom(i,filename);
					break; 
				}
				currentIndex++;
			}
		}
		return true;
//		if(Arrays.asList(infoarray[i]).contains(mangeType)){
//			
//		}
 
	}
}
